/*
 * @Description: 框选功能
 * @Author: wangqian
 * @LastEditors: wangqian
 * @Date: 2021-01-03 14:28:53
 * @LastEditTime: 2021-01-14 20:47:45
 */
export default class BoxSelection {
  constructor(props) {
    //这里初始化class的时候需要传map对象进来
    this.map = props;
    this.source;
    this.layer;
    this.draw;
    //样式
    this.style = new ol.style.Style({
      fill: new ol.style.Fill({
        color: 'rgba(96,96,96, 0.1)',
      }),
      //划线的时候的图样
      stroke: new ol.style.Stroke({
        color: 'red',
        width: 2,
      }),
      image: new ol.style.Circle({
        radius: 5,
        stroke: new ol.style.Stroke({
          color: 'rgba(96,96,96, 0.1)',
        }),
        fill: new ol.style.Fill({
          color: 'rgba(96,96,96, 0.1)',
        }),
      }),
    });
    this.init();
  }
  init() {
    //临时图层的数据源
    this.source = new ol.source.Vector();
    //新建临时图层，并设置临时图层渲染各种要素的样式
    this.layer = new ol.layer.Vector({
      source: this.source,
      style: this.style,
    });
  }
  /**
   * @description: 框选
   * @param {String} type Rect | Circle
   * @param {Function} callback 框选结束后的回调函数
   * @return {*}
   */
  drawArea(type, callback) {
    this.remove();

    let geometryFunction;
    if (type === 'Circle') {
      geometryFunction = undefined;
    } else if (type === 'Rect') {
      geometryFunction = function (coordinates, geometry) {
        if (!geometry) {
          geometry = new ol.geom.Polygon(null);
        }
        var start = coordinates[0];
        var end = coordinates[1];
        geometry.setCoordinates([[start, [start[0], end[1]], end, [end[0], start[1]], start]]);
        return geometry;
      };
    } else {
      return;
    }

    this.draw = new ol.interaction.Draw({
      source: this.source,
      type: 'Circle',
      style: this.style,
      geometryFunction,
    });
    this.map.addInteraction(this.draw);
    this.draw.on('drawend', evt => {
      var extent = evt.feature.getGeometry().getExtent(); // 获取经纬度范围
      this.map.addLayer(this.layer);
      callback(extent);
    });
  }
  remove() {
    console.log('remove');
    this.layer.getSource().clear();
    this.layer && this.map.removeLayer(this.layer);
    this.draw && this.map.removeInteraction(this.draw);
  }
  // 当页面退出
  destroy() {
    this.remove();
    this.map = null;
  }
}
